﻿using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Paddings;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;

namespace com.iot.core.util
{
    public class Keys
    {
        private static string key = "1234567890123iot";
        public static string Encrypt(string encryptStr )
        {
            if (string.IsNullOrEmpty(encryptStr)) return null;
            Byte[] toEncryptArray = Encoding.UTF8.GetBytes(encryptStr);
            RijndaelManaged rm = new RijndaelManaged
            {
                Key = Encoding.UTF8.GetBytes(key),
                Mode = CipherMode.ECB,
                Padding = PaddingMode.PKCS7
            };
            ICryptoTransform cTransform = rm.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return ByteUtil.ByteToHex(resultArray) ;
            //需要UTF8处理一下，否则
           //return Convert.ToBase64String(Encoding.UTF8.GetBytes(Convert.ToBase64String(resultArray, 0, resultArray.Length))); 
        }
        public static string Decrypt(string decryptStr)
        {
            if (string.IsNullOrEmpty(decryptStr)) return null;
            byte[] toEncryptArray = ByteUtil.HexstrToByte(decryptStr);
            RijndaelManaged rm = new RijndaelManaged
            {
                Key = Encoding.UTF8.GetBytes(key),
                Mode = CipherMode.ECB,
                Padding = PaddingMode.PKCS7
            };
            ICryptoTransform cTransform = rm.CreateDecryptor();
            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return Encoding.UTF8.GetString(resultArray);
        }
    }
}
